<template>
  <view class="w-100 bac-col-fa bottom-index min-h-100">
    <!-- 加载中蒙版 -->
    <qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
    <view
        :style="{position:'sticky',height:menuObject.height + menuObject.top +8 + 'px',width:'100%',zIndex:'10',top:0}"
        class="w-100 vague-bgfa-8 bac-col-f">
      <view class="flex-dir-row "
            :style="{top:menuObject.top + 'px',height:menuObject.height + 'px',lineHeight:menuObject.height+'px',position:'sticky'}">
        <view v-if="!searchState" @click="stateClick('open')" class="iconfont ic-sousuo1 fs-46 ml-30 dh-1s"
              :class="searchState?'animate__fadeOut ':'animate__fadeIn'"></view>
        <view v-if="searchState" class="search col-0a2e36 bac-col-0a20a flex-dir-row ali-item-cen w-100"
              :style="{ width: searchWidth + 'rpx',transition: 'width 0.5s ease-in-out,padding 0.3s ease-in-out',padding:searcPadding+'rpx'}">
          <text class="iconfont ic-sousuo fs-40 mr-10 col-00ba31"></text>
          <input class="fs-24 w-100 col-0a2e36" type="text" confirm-type="search" v-model="searchText"
                 placeholder-style="color:#0a2e365e" placeholder="点击搜索圈子" @confirm="fuzzySearch"/>
          <text class="iconfont ic-qingchu fs-40" @click="stateClick('close')"></text>
        </view>
        <view v-if="!searchState" class="flex-dir-row  pos-abso flex-x-bet  dh-1s centered"
              :class="searchState?'animate__fadeOut ':'animate__fadeIn'">
          <view class="top-tab-container">
            <v-tabs ref="tabs" :zIndex="1" bgColor="#ffffff00" pillsColor="#ffffff00" fontSize="30rpx"
                    pillsStyle="box" activeFontSize="30rpx" lineHeight="0rpx" :lineScale="0.3" bold
                    activeColor="linear-gradient(to right, #000000, #000000)" paddingItem="0rpx 40rpx"
                    color="linear-gradient(to right, #000000, #000000)" lineColor="#616161" v-model="currentTab"
                    :tabs="['话题','圈子']"
                    @change="(e)=> e==0?switchContentType('topic'):switchContentType('circle')"></v-tabs>
          </view>
        </view>
      </view>
    </view>
    <!-- 轮播图区域 -->
    <view class="banner-container">
      <z-swiper ref="zSwiper" v-model="bannerList" :options="options" @slideChange="onSwiperChange">
        <z-swiper-item v-for="(item, index) in bannerList" :key="index" @click="switchToTopicFromBanner(item.topicId)">
          <image :src="item.imageUrl" mode="scaleToFill" class="banner-image"/>
          <view class="banner-info">
            <view class="banner-content">
              <text class="banner-title">{{ item.title }}</text>
              <text class="banner-desc">{{ item.description }}</text>
            </view>
            <view class="banner-btn whi-sp flex-shrink-0">进入话题</view>
          </view>
        </z-swiper-item>
      </z-swiper>
      <view class="banner-indicator">
        <view class="indicator-dot" v-for="(item, index) in bannerNum" :key="index"
              :class="{ active: currentSwiper === index }" @click="changeSwiper(index)"></view>
      </view>
    </view>

    <!-- 内容切换区域，添加动画容器 -->
    <view class="content-container">
      <!-- 话题分类部分 -->
      <view class="content-item" :class="{'active': contentType === 'topic', 'next': contentType === 'circle'}">
        <view class="ping-20">
          <view>


            <!-- 话题下的圈子列表 - 瀑布流形???-->
            <view v-if="selectedTopicId" class="mt-20 topic-content">
              <!-- 话题简???-->
              <view class="topic-detail" v-if="selectedTopic">
                <view class="topic-detail-header"
                      @click="$NavigateTo(`/pages/detail/topicDetail?id=${selectedTopic.id}`)">
                  <image class="topic-detail-cover" :src="selectedTopic.coverImage" mode="aspectFill"
                         lazy-load>
                  </image>
                  <view class="topic-detail-info">
                    <view class="topic-detail-name">{{ selectedTopic.name }}</view>
                    <view class="topic-detail-stats">
                      <text>{{ selectedTopic.postsCount || 0 }} 内容</text>
                      <text class="ml-10">{{ selectedTopic.followersCount || 0 }} 关注</text>
                    </view>
                    <view class="topic-detail-desc text-element-2">{{ selectedTopic.description }}
                    </view>
                  </view>
                  <view class="iconfont ic-you fs-40 ml-10 col-87"></view>
                </view>
              </view>

              <!-- 话题下无圈子时的空状???-->
              <view v-if="topicCircleList.length === 0 && !topicLoading" class="pos-rela"
                    style="height: 30vh;">
                <view class="activity-empty-box">
                  <image class="activity-empty-image"
                         src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/circle-empty.png"
                         mode="scaleToFill"/>
                  <view class="fs-28 col-b1">该话题下暂无内容</view>
                </view>
              </view>

              <!-- 话题下的圈子瀑布???-->
              <view v-else class="mt-10">
                <view class="flex-x-bet">
                  <view class="waterfall-column">
                    <view class="mb-20 bac-col-f br-10 overflow-h circle-item"
                          v-for="(item, index) in topicCircleListLeft" :key="index">
                      <image @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)"
                             :src="item.thumbnail[0]" mode="widthFix"
                             style="width: 100%;height: auto;display: block;" lazy-load>
                      </image>
                      <view class="ping-20">
                        <view class="item-title fs-28 text-element-2"
                              @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)">
                          {{ item.title }}
                        </view>
                        <view class="flex-x-bet ali-item-cen mt-10 fs-24">
                          <view
                              @click="$NavigateTo(`/qmy_user/user/myPage?usid=${item.user_id}`)"
                              class="flex-1 ali-item-cen">
                            <qmy-gender-border iconWidth="15rpx" iconHeight="15rpx"
                                               iconSize="12rpx" iconLineHeight="15rpx"
                                               :gender="item.user_gender"
                                               :avatar="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
                                               :avatarWidth="40 + 'rpx'"
                                               :avatarHeight="40 + 'rpx'"></qmy-gender-border>
                            <text
                                class="nickname col-87 text-element-1 ml-10">{{ item.user_name || '匿名用户' }}
                            </text>
                          </view>
                          <view @click="likeCircle(item._id)"
                                class="col-b1 ali-item-cen like-btn"
                                hover-class="like-btn-hover">
                            <view class="iconfont fs-40"
                                  :class="item.like_user_id.includes(userInfo.id)?'ic-nice col-00ba31':'ic-nice-line'">
                            </view>
                            <view class="fs-24 ml-5">{{ item.like_user_id.length || 0 }}
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                  <view class="waterfall-column">
                    <view class="mb-20 bac-col-f br-10 overflow-h circle-item"
                          v-for="(item, index) in topicCircleListRight" :key="index">
                      <image @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)"
                             :src="item.thumbnail[0]" mode="widthFix"
                             style="width: 100%;height: auto;display: block;" lazy-load>
                      </image>
                      <view class="ping-20">
                        <view class="item-title fs-28 text-element-2"
                              @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)">
                          {{ item.title }}
                        </view>
                        <view class="flex-x-bet ali-item-cen mt-10 fs-24">
                          <view
                              @click="$NavigateTo(`/qmy_user/user/myPage?usid=${item.user_id}`)"
                              class="flex-1 ali-item-cen">
                            <qmy-gender-border iconWidth="15rpx" iconHeight="15rpx"
                                               iconSize="12rpx" iconLineHeight="15rpx"
                                               :gender="item.user_gender"
                                               :avatar="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
                                               :avatarWidth="40 + 'rpx'"
                                               :avatarHeight="40 + 'rpx'"></qmy-gender-border>
                            <text
                                class="nickname col-87 text-element-1 ml-10">{{ item.user_name || '匿名用户' }}
                            </text>
                          </view>
                          <view @click="likeCircle(item._id)"
                                class="col-b1 ali-item-cen like-btn"
                                hover-class="like-btn-hover">
                            <view class="iconfont fs-40"
                                  :class="item.like_user_id.includes(userInfo.id)?'ic-nice col-00ba31':'ic-nice-line'">
                            </view>
                            <view class="fs-24 ml-5">{{ item.like_user_id.length || 0 }}
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 话题分类底部logo -->
          <qmy-logo v-if="topicCircleList.length || topicLoading" :loading="topicLoading"></qmy-logo>
        </view>
      </view>

      <!-- 圈子部分 -->
      <view class="content-item " :class="{'active': contentType === 'circle', 'prev': contentType === 'topic'}">
        <view class="vague-bg-8">
          <v-tabs :pills="true" :scroll="false" :zIndex="1" bgColor="#ffffff00" pillsColor="#ffffff00"
                  fontSize="28rpx" activeFontSize="30rpx" lineHeight="40rpx"
                  activeColor="linear-gradient(to right, #000000, #000000)"
                  color="linear-gradient(to right, #000000, #000000)" bold lineColor="#14cc60" v-model="current"
                  paddingItem="0 20rpx 0 0" :tabs="tabs" @change="changeTab"></v-tabs>
        </view>
        <view class="ping-20">
          <view>
            <!-- 如果圈子列表为空 -->
            <view v-if="circleList.length == 0" class="pos-rela" style="height: 30vh;">
              <view class="activity-empty-box">
                <image class="activity-empty-image"
                       src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/circle-empty.png"
                       mode="scaleToFill"/>
                <view class="fs-28 col-b1">暂无圈子</view>
              </view>
            </view>

            <!-- 圈子瀑布???-->
            <view v-else>
              <view class="flex-x-bet">
                <view class="waterfall-column">
                  <view class="mb-20 bac-col-f br-10 overflow-h circle-item"
                        v-for="(item, index) in circleListLeft" :key="index">
                    <image @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)"
                           :src="item.thumbnail[0]" mode="widthFix"
                           style="width: 100%;height: auto;display: block;" lazy-load>
                    </image>
                    <view class="ping-20">
                      <view class="item-title fs-28 text-element-2"
                            @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)">
                        {{ item.title }}
                      </view>
                      <view class="flex-x-bet ali-item-cen mt-10 fs-24">
                        <view @click="$NavigateTo(`/qmy_user/user/myPage?usid=${item.user_id}`)"
                              class="flex-1 ali-item-cen">
                          <qmy-gender-border iconWidth="15rpx" iconHeight="15rpx"
                                             iconSize="12rpx" iconLineHeight="15rpx"
                                             :gender="item.user_gender"
                                             :avatar="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
                                             :avatarWidth="40 + 'rpx'"
                                             :avatarHeight="40 + 'rpx'"></qmy-gender-border>
                          <text
                              class="nickname col-87 text-element-1 ml-10">{{ item.user_name || '匿名用户' }}
                          </text>
                        </view>
                        <view @click="likeCircle(item._id)" class="col-b1 ali-item-cen like-btn"
                              hover-class="like-btn-hover">
                          <view class="iconfont fs-40"
                                :class="item.like_user_id.includes(userInfo.id)?'ic-nice col-00ba31':'ic-nice-line'">
                          </view>
                          <view class="fs-24 ml-5">{{ item.like_user_id.length || 0 }}</view>
                        </view>
                      </view>
                      <view v-if="item.category_id" @click="switchToTopic(item.category_id)"
                            class="topic-tag mt-10" hover-class="topic-tag-hover">
                        <view class="fs-20">{{ item.topic_name || '话题' }}</view>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="waterfall-column">
                  <view class="mb-20 bac-col-f br-10 overflow-h circle-item"
                        v-for="(item, index) in circleListRight" :key="index">
                    <image @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)"
                           :src="item.thumbnail[0]" mode="widthFix"
                           style="width: 100%;height: auto;display: block;" lazy-load>
                    </image>
                    <view class="ping-20">
                      <view class="item-title fs-28 text-element-2"
                            @click="$NavigateTo(`/pages/detail/articleDetail?id=${item._id}`)">
                        {{ item.title }}
                      </view>
                      <view class="flex-x-bet ali-item-cen mt-10 fs-24">
                        <view @click="$NavigateTo(`/qmy_user/user/myPage?usid=${item.user_id}`)"
                              class="flex-1 ali-item-cen">
                          <qmy-gender-border iconWidth="15rpx" iconHeight="15rpx"
                                             iconSize="12rpx" iconLineHeight="15rpx"
                                             :gender="item.user_gender"
                                             :avatar="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
                                             :avatarWidth="40 + 'rpx'"
                                             :avatarHeight="40 + 'rpx'"></qmy-gender-border>
                          <text
                              class="nickname col-87 text-element-1 ml-10">{{ item.user_name || '匿名用户' }}
                          </text>
                        </view>
                        <view @click="likeCircle(item._id)" class="col-b1 ali-item-cen like-btn"
                              hover-class="like-btn-hover">
                          <view class="iconfont fs-40"
                                :class="item.like_user_id.includes(userInfo.id)?'ic-nice col-00ba31':'ic-nice-line'">
                          </view>
                          <view class="fs-24 ml-5">{{ item.like_user_id.length || 0 }}</view>
                        </view>
                      </view>
                      <view v-if="item.category_id" @click="switchToTopic(item.category_id)"
                            class="topic-tag mt-10" hover-class="topic-tag-hover">
                        <view class="fs-20">{{ item.topic_name || '话题' }}</view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <!-- 底部logo -->
            <!-- <qmy-logo :loading="load"></qmy-logo> -->
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  store,
  mutations
} from '@/utils/store.js'
import { getTopicListApi } from '@/api/topic/topic.js'
import { getAllPostListApi, getRecommendPostListApi } from '@/api/post/posts.js'
import { getBannerListApi } from '@/api/banner/banner.js'
export default {
  name: 'pageB',
  props: {
    scrollTop: {
      type: Number,
      required: 0
    },
    page: {
      type: Number,
      required: 0
    },
    pageSize: {
      type: Number,
      required: 10
    },
    isVisible: {
      type: Boolean,
      required: false
    },
    refresh: {
      type: Boolean,
      required: false
    }
  },
  computed: {
    userInfo() {
      return store.userInfo //用户信息
    },
  },
  data() {
    return {
      bannerType: 'topic',
      // #ifdef MP-WEIXIN
      menuObject: uni.getMenuButtonBoundingClientRect(),
      // #endif
      // #ifndef MP-WEIXIN
      menuObject: {
        top: 19,
        height: 36,
        width: 77
      },
      // #endif
      searchState: false,
      searchWidth: 0, //搜索框宽???
      searcPadding: 0,
      current: 0,
      tabs: ['最新', '精选', '推荐', '热门'],
      // 轮播相关数据
      bannerList: [], //轮播数据
      bannerNum: [], //轮播指示点数据
      currentSwiper: 0, //当前轮播索引
      options: {
        effect: 'panorama',
        loop: true, //无限循环
        slidesPerView: 1.4,
        centeredSlides: true,
        panorama: {
          depth: 0,
          rotate: 45,
          stretch: 1.2
        },
      },
      activityData: [], //精选活???
      circleList: [], //圈子列表
      circleListLeft: [], //圈子列表左列
      circleListRight: [], //圈子列表右列
      allCircleList: [], // 所有圈子数据（用于前端筛选）
      pageStop: false, //分页是否停止
      searchText: '', //搜索框内???
      dataLoaded: false, //数据是否加载完成
      load: false, // 是否加载???
      contentType: 'topic', // 内容类型：话题或圈子
      prevContentType: 'topic', // 上一个内容类型，用于动画效果
      topicList: [], // 话题列表
      selectedTopicId: null, // 选中的话题ID
      selectedTopic: null, // 选中的话题对???
      topicCircleList: [], // 话题下的圈子列表
      topicCircleListLeft: [], // 话题下的圈子列表左列
      topicCircleListRight: [], // 话题下的圈子列表右列
      topicLoading: false, // 话题加载???
      // 添加缓存数据结构
      cachedCircleData: {}, // 缓存各标签下的圈子数???{tabIndex: {page: data}}
      cachedTopicCircleData: {}, // 缓存各话题下的圈子数???{topicId: data}
      currentTab: 0
    }
  },
  mounted(){
    // 并行执行所有异步请求
      Promise.all([
        this.getTopicList(),
        this.getCircleList(),
        this.getBannerList()
      ]).then(() => {
        // 所有请求完成（无论成功失败）后，设置 dataLoaded 为 true
        // 默认选择第一个
        if (this.topicList.length > 0 && !this.selectedTopicId) {
          this.selectedTopicId = this.topicList[0].id;
          this.selectedTopic = this.topicList[0];
          console.log("第一个话题数据：",this.selectedTopic);
          console.log("topics数据：",this.allCircleList[0].topics);
          // 设置话题下的圈子列表（筛选属于该话题的圈子）
          this.topicCircleList = this.allCircleList.filter(item => 
          item.topics && Array.isArray(item.topics) ? item.topics.includes(this.selectedTopicId) : false);
          this.topicCircleListLeft = this.topicCircleList.slice(0, Math.ceil(this.topicCircleList.length / 2));
          this.topicCircleListRight = this.topicCircleList.slice(Math.ceil(this.topicCircleList.length / 2));
        }
        // 根据当前选中的标签过滤数???
        this.filterCircleListByTab();
        this.dataLoaded = true;
        this.pageStop = true; 
        this.topicLoading = false;
      });
  },
  watch: {
    page(e) {
      console.log("contentType切换：",e);
      if (e != 0) {
        console.log("contentType值------：",this.contentType);
        // 如果处于圈子视图，则获取圈子列表
        if (this.contentType === 'circle') {
          this.getCircleList();
        }
      }
    },
    scrollTop(e) {
      if (this.searchState && !this.searchText) {
        this.searchWidth = 0;
        this.searcPadding = 0;
        setTimeout(() => {
          this.searchState = false;
        }, 500)
      }
    },
    isVisible(val) {
      if (val && !this.dataLoaded) {
        // 使用模拟数据
        this.initMockData();
      }
    },
    refresh(e) {
      if (e) {
        this.contentType = 'topic'
        this.dataLoaded = false;
        this.searchText = ''; //清空搜索框内???
        // 清空所有数???
        this.allCircleList = [];
        this.circleList = [];
        this.circleListLeft = [];
        this.circleListRight = [];
        this.topicCircleList = [];
        this.topicCircleListLeft = [];
        this.topicCircleListRight = [];
        this.selectedTopicId = null;
        this.selectedTopic = null;
        this.pageStop = false; //分页停止
        this.$emit('resetPage', 0) //重置分页页码
        this.searchWidth = 0;
        this.searcPadding = 0;
        setTimeout(() => {
          this.searchState = false;
        }, 500)
        this.$nextTick(() => {
          // 重新初始化模拟数???
          this.initMockData();
        })
      }
    }
  },
  methods: {

    // 初始化模拟数???
    initMockData() {
      // 模拟话题列表数据
      this.topicList = [
        {
          _id: 'topic1',
          name: '户外探险',
          icon: 'https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp',
          description: '分享户外探险经历，交流探险技巧和装备',
          post_count: 156,
          follow_count: 1240
        },
        {
          _id: 'topic2',
          name: '美食分享',
          icon: 'https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp',
          description: '分享户外探险经历，交流探险技巧和装备',
          post_count: 89,
          follow_count: 856
        },
        {
          _id: 'topic3',
          name: '摄影技',
          icon: 'https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp',
          description: '摄影技巧交流，作品展示',
          post_count: 234,
          follow_count: 2100
        },
        {
          _id: 'topic4',
          name: '读书心得',
          icon: 'https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp',
          description: '分享户外探险经历，交流探险技巧和装备',
          post_count: 67,
          follow_count: 543
        },
        {
          _id: 'topic5',
          name: '运动健身',
          icon: 'https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp',
          description: '分享户外探险经历，交流探险技巧和装备',
          post_count: 178,
          follow_count: 1567
        }
      ];

      // 创建话题轮播数据
      this.bannerList = [
        {
          bannerfile: 'https://picsum.photos/750/800?random=21',
          title: '户外探险话题',
          description: '分享户外探险经历，交流探险技巧和装备',
          topicId: 'topic1'
        },
        {
          bannerfile: 'https://picsum.photos/750/800?random=22',
          title: '美食分享话题',
          description: '发现美食，分享制作心得和用餐体验',
          topicId: 'topic2'
        },
        {
          bannerfile: 'https://picsum.photos/750/800?random=23',
          title: '摄影技巧话题',
          description: '摄影技巧交流，作品展示和心得分享',
          topicId: 'topic3'
        },
        {
          bannerfile: 'https://picsum.photos/750/800?random=24',
          title: '读书心得话题',
          description: '好书推荐，读书心得和知识分享',
          topicId: 'topic4'
        },
        {
          bannerfile: 'https://picsum.photos/750/800?random=25',
          title: '运动健身话题',
          description: '健身经验分享，运动技巧和健康生活',
          topicId: 'topic5'
        }
      ];
      this.bannerNum = [...this.bannerList];

      // 初始化时自动选择第一个话题
      if (this.bannerList.length > 0) {
        this.selectTopic(this.bannerList[0].toDetailId);
      }

      // 模拟圈子列表数据
      this.allCircleList = [
        {
          _id: 'circle1',
          title: '春日登山记录，遇见最美的风景',
          thumbnail: ['https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp'],
          user_id: 'user1',
          user_name: '分享户',
          user_avatar: 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg',
          user_gender: 1,
          like_user_id: ['user2', 'user3', 'user4'],
          category_id: 'topic1',
          topic_name: '户外探险',
          publish_date: Date.now() - 86400000, // 1天前
          last_modify_date: Date.now() - 86400000,
          is_essence: false,
          is_sticky: false
        },
        {
          _id: 'circle2',
          title: '自制红烧肉的秘密配方',
          thumbnail: ['https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp'],
          user_id: 'user2',
          user_name: '厨房小能',
          user_avatar: 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg',
          user_gender: 2,
          like_user_id: ['user1', 'user3', 'user5', 'user6'],
          category_id: 'topic2',
          topic_name: '美食分享',
          publish_date: Date.now() - 172800000, // 2天前
          last_modify_date: Date.now() - 172800000,
          is_essence: true,
          is_sticky: false
        },
        {
          _id: 'circle3',
          title: '夜景摄影技巧分',
          thumbnail: ['https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp'],
          user_id: 'user3',
          user_name: '光影大师',
          user_avatar: 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg',
          user_gender: 1,
          like_user_id: ['user1', 'user2', 'user4', 'user5', 'user6', 'user7'],
          category_id: 'topic3',
          topic_name: '摄影技',
          publish_date: Date.now() - 259200000, // 3天前
          last_modify_date: Date.now() - 259200000,
          is_essence: false,
          is_sticky: true
        },
        {
          _id: 'circle4',
          title: '《百年孤独》读后感',
          thumbnail: ['https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp'],
          user_id: 'user4',
          user_name: '文学爱好',
          user_avatar: 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg',
          user_gender: 2,
          like_user_id: ['user2', 'user5'],
          category_id: 'topic4',
          topic_name: '读书心得',
          publish_date: Date.now() - 345600000, // 4天前
          last_modify_date: Date.now() - 345600000,
          is_essence: false,
          is_sticky: false
        },
        {
          _id: 'circle5',
          title: '健身房训练计划制',
          thumbnail: ['https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp'],
          user_id: 'user5',
          user_name: '健身达人',
          user_avatar: 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg',
          user_gender: 1,
          like_user_id: ['user1', 'user3', 'user4', 'user6'],
          category_id: 'topic5',
          topic_name: '运动健身',
          publish_date: Date.now() - 432000000, // 5天前
          last_modify_date: Date.now() - 432000000,
          is_essence: true,
          is_sticky: false
        },
        {
          _id: 'circle6',
          title: '城市徒步路线推荐',
          thumbnail: ['https://gd-hbimg.huaban.com/dbd4180e2ffffcde1bddda12023f91123e4b7f796bb58-R4btzp'],
          user_id: 'user6',
          user_name: '城市探索',
          user_avatar: 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg',
          user_gender: 2,
          like_user_id: ['user1', 'user2'],
          category_id: 'topic1',
          topic_name: '户外探险',
          publish_date: Date.now() - 518400000, // 6天前
          last_modify_date: Date.now() - 518400000,
          is_essence: false,
          is_sticky: false
        }
      ];

      // 默认选择第一个话???
      if (this.topicList.length > 0 && !this.selectedTopicId) {
        this.selectedTopicId = this.topicList[0].id;
        this.selectedTopic = this.topicList[0];

        // 设置话题下的圈子列表（筛选属于该话题的圈子）
        this.topicCircleList = this.allCircleList.filter(item =>
        item.topics && Array.isArray(item.topics) ? item.topics.includes(this.selectedTopicId) : false);
        this.topicCircleListLeft = this.topicCircleList.slice(0, Math.ceil(this.topicCircleList.length / 2));
        this.topicCircleListRight = this.topicCircleList.slice(Math.ceil(this.topicCircleList.length / 2));
      }

      // 根据当前选中的标签过滤数???
      this.filterCircleListByTab();

      // 设置数据加载完成
      this.dataLoaded = true;
      this.pageStop = true; // 模拟数据已全部加???
      this.topicLoading = true;
    },

    // 切换内容类型：话???圈子
    switchContentType(type) {
      if (this.contentType === type) return;

      // 记录上一个内容类型，用于动画效果
      this.prevContentType = this.contentType;
      this.contentType = type;
    },
    // 获取话题轮播图数据
    async getBannerList() {
      try {
        const res = await getBannerListApi(this.bannerType);
        if ( res.data.code === 200 ) {
          this.bannerList = res.data.data;
          
        }else {
          this.$Toast("获取话题轮播图失败")
        }
      } catch (e) {
        console.log("获取轮播图数据异常",e);
      }
    },
    async getCircleList() {
      try{
        const res = await getAllPostListApi();
        if ( res.data.code === 200 ){
          this.allCircleList = res.data.data.records;
          this.allCircleList.map( item => {
            item.images = JSON.parse(item.images);
            item.tags = JSON.parse(item.tags);
            item.topics = JSON.parse(item.topics);
          })
          console.log("获取圈子列表关联的topics类型:",typeof(this.allCircleList[0].topics));
          console.log(Array.isArray(this.allCircleList[0].topics)); 
        }else{
          this.$Toast("获取圈子列表失败");
        }
      }catch(e){
          console.log("获取圈子列表失败", e);
      }
    },
    // 获取话题列表
    async getTopicList() {
      
      try{
        const res = await getTopicListApi();
        if ( res.data.code === 200 ){
          this.topicList = res.data.data;
          console.log("获取话题列表:",this.topicList)
        }else{
          this.$Toast("获取话题列表失败");
        }
      }catch(e){
          console.log("获取话题列表失败", e);
      }
    },
    // 选择话题
    selectTopic(id) {
      this.selectedTopicId = id;
      // 从topicList中查找选中的话???
      this.selectedTopic = this.topicList.find(item => item.id === id);

      // 使用模拟数据，筛选属于该话题的圈???
      this.topicCircleList = this.allCircleList.filter(item => item.topics.includes(id));
      this.topicCircleListLeft = this.topicCircleList.slice(0, Math.ceil(this.topicCircleList.length / 2));
      this.topicCircleListRight = this.topicCircleList.slice(Math.ceil(this.topicCircleList.length / 2));
    },
    // 获取话题下的圈子列表
    getTopicCircleList() {
      // 使用模拟数据，已在selectTopic中处???
      console.log('获取话题下的圈子列表 - 使用模拟数据');
    },
    // 根据选中的标签过滤圈子列???
    filterCircleListByTab() {
      let tempList = [...this.allCircleList];

      // 根据标签排序
      if (this.current === 0) {
        // 最新：按发布时间或修改时间排序
        tempList.sort((a, b) => {
          const dateA = new Date(a.updateTime || a.createTime);
          const dateB = new Date(b.updateTime || b.createTime);
          return dateB - dateA;
        });
      } else if (this.current === 1) {
        // 精选：优先显示精华内容
        tempList.sort((a, b) => {
          if (a.isTop === b.isTop) {
            const dateA = new Date(a.updateTime || a.createTime);
            const dateB = new Date(b.updateTime || b.createTime);
            return dateB - dateA;
          }
          return (b.isTop || 0) - (a.isTop || 0);
        });
      } else if (this.current === 2) {
        // 推荐：优先显示置顶内???
        tempList.sort((a, b) => {
          if (a.isRecommend === b.isRecommend) {
            const dateA = new Date(a.updateTime || a.createTime);
            const dateB = new Date(b.updateTime || b.createTime);
            return dateB - dateA;
          }
          return (b.isRecommend || 0) - (a.isRecommend || 0);
        });
      } else if (this.current === 3) {
        // 热门：按点赞数排???
        tempList.sort((a, b) => {
          if (a.isHot === b.isHot) {
              const dateA = new Date(a.updateTime || a.createTime);
              const dateB = new Date(b.updateTime || b.createTime);
              return dateB - dateA;
            }
            return (b.isHot || 0) - (a.isHot || 0);
          });
      }

      // 更新圈子列表和瀑布???
      this.circleList = tempList;
      this.circleListLeft = this.circleList.slice(0, Math.ceil(this.circleList.length / 2));
      this.circleListRight = this.circleList.slice(Math.ceil(this.circleList.length / 2));
    },
    // 模糊搜索
    fuzzySearch() {
      console.log('模糊搜索 - 使用模拟数据', this.searchText);
      this.contentType = 'circle';

      // 如果有搜索内容，筛选圈子列???
      if (this.searchText.trim()) {
        const filteredList = this.allCircleList.filter(item =>
            item.title.includes(this.searchText) ||
            item.user_name.includes(this.searchText) ||
            item.topic_name.includes(this.searchText)
        );
        this.circleList = filteredList;
      } else {
        // 无搜索内容时显示所有数???
        this.filterCircleListByTab();
      }

      // 更新瀑布流布局
      this.circleListLeft = this.circleList.slice(0, Math.ceil(this.circleList.length / 2));
      this.circleListRight = this.circleList.slice(Math.ceil(this.circleList.length / 2));
    },
    // 切换标签
    changeTab(index) {
      this.current = index;

      // 直接进行前端筛???
      this.filterCircleListByTab();
    },
    //点赞、取消点???
    likeCircle(id) {
      // 点赞节流
      this.$debounce(() => {
        // 震动
        uni.vibrateShort();

        // 模拟用户ID（因为没有真实登录）
        const mockUserId = 'currentUser';

        // 更新圈子列表中的点赞状???
        if (this.contentType === 'circle') {
          this.circleList.forEach(item => {
            if (item._id == id) {
              item.like_user_id.includes(mockUserId) ?
                  item.like_user_id.splice(item.like_user_id.indexOf(mockUserId), 1) :
                  item.like_user_id.push(mockUserId);
            }
          })
          // 同时更新allCircleList中的数据
          this.allCircleList.forEach(item => {
            if (item._id == id) {
              item.like_user_id.includes(mockUserId) ?
                  item.like_user_id.splice(item.like_user_id.indexOf(mockUserId), 1) :
                  item.like_user_id.push(mockUserId);
            }
          })
        }
        // 更新话题下圈子列表中的点赞状???
        else if (this.contentType === 'topic') {
          this.topicCircleList.forEach(item => {
            if (item._id == id) {
              item.like_user_id.includes(mockUserId) ?
                  item.like_user_id.splice(item.like_user_id.indexOf(mockUserId), 1) :
                  item.like_user_id.push(mockUserId);
            }
          })
          // 同时更新allCircleList中的数据
          this.allCircleList.forEach(item => {
            if (item._id == id) {
              item.like_user_id.includes(mockUserId) ?
                  item.like_user_id.splice(item.like_user_id.indexOf(mockUserId), 1) :
                  item.like_user_id.push(mockUserId);
            }
          })
          // 更新左右两列数据（瀑布流）
          this.topicCircleListLeft = this.topicCircleList.slice(0, Math.ceil(this.topicCircleList.length / 2));
          this.topicCircleListRight = this.topicCircleList.slice(Math.ceil(this.topicCircleList.length / 2));
        }

        console.log('点赞操作 - 使用模拟数据', id);
      }, 500, true, "likeCircle")
    },
    //搜索框状???
    stateClick(e) {
      if (e == 'open') {
        this.searchState = true;
        setTimeout(() => {
          // #ifdef MP-WEIXIN
          this.searchWidth = 710 - (this.menuObject.width * 2);
          // #endif
          // #ifndef MP-WEIXIN
          this.searchWidth = 750;
          // #endif
          this.searcPadding = 20;
        }, 10)
      } else {
        this.contentType = 'topic'
        this.searchText = ''; //清空搜索框内???
        this.searchWidth = 0; //搜索框宽???
        this.searcPadding = 0; //搜索框padding
        setTimeout(() => {
          this.searchState = false; //搜索框状???
        }, 500)
      }
    },
    clearCache() {
      this.cachedTopicCircleData = {}; // 只清除话题缓???
      this.allCircleList = []; // 清除圈子列表缓存
    },
    // 切换到话题并选择指定话题
    switchToTopic(topicId) {
      this.switchContentType('topic');
      this.currentTab = 0; // 更新v-tabs组件的选中状???
      this.$nextTick(() => {
        this.selectTopic(topicId);
      });
    },
    
    // 轮播图切换事件
    onSwiperChange(swiper, index) {
      // z-swiper在循环模式下实际数据结构为 [最后一项, 原始数据, 第一项]
      let realIndex = index;
      if (this.bannerNum.length > 0) {
        // 全景模式下，swiper会返回实际的索引，不需要再减1
        realIndex = Math.abs(index);
        // 处理边界情况
        if (realIndex >= this.bannerNum.length) {
          realIndex = realIndex % this.bannerNum.length;
        } else if (realIndex < 0) {
          realIndex = (realIndex + this.bannerNum.length) % this.bannerNum.length;
        }
        this.currentSwiper = realIndex;
        
        // 自动加载对应话题的内容
        if (this.bannerList[realIndex] && this.bannerList[realIndex].toDetailId) {
          this.autoLoadTopicContent(this.bannerList[realIndex].toDetailId);
        }
      }
    },
    
    // 自动加载话题内容
    autoLoadTopicContent(topicId) {
      // 切换到话题视图
      this.switchContentType('topic');
      this.currentTab = 0;
      
      // 使用selectTopic方法加载话题内容
      this.selectTopic(topicId);
    },
    
    // 从轮播切换到话题
    switchToTopicFromBanner(topicId) {
      // 切换到话题视图
      this.switchContentType('topic');
      this.currentTab = 0; // 更新v-tabs组件的选中状态
      this.$nextTick(() => {
        // 选择对应的话题
        this.selectTopic(topicId);
      });
    },
    
    // 点击指示点切换轮播
    changeSwiper(index) {
      if (this.$refs.zSwiper && this.$refs.zSwiper.swiper) {
        // 直接跳转到指定索引
        // 因为z-swiper的循环模式会自动处理边界情况
        this.$refs.zSwiper.swiper.slideTo(index);
        this.currentSwiper = index;
      }
    }
  }
}
</script>

<style>
/* 轮播图 */
.banner-container {
  position: relative;
  padding: 0;
  background-color: #fff;
  width: 100%;
}

.banner-image {
  height: 800rpx;
  width: 100%;
  overflow: hidden;
}

.banner-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 40rpx;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.3) 50%, transparent);
}

.banner-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  max-width: 70%;
}

.banner-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  margin-bottom: 10rpx;
}

.banner-desc {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.95);
  margin-bottom: 10rpx;
}

.banner-btn {
  display: inline-block;
  padding: 12rpx 30rpx;
  background: linear-gradient(to right, #14cc60, #0fb353);
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #fff;
  font-weight: 500;
  box-shadow: 0 4px 10px rgba(20, 204, 96, 0.4);
  transition: transform 0.2s;
}

.banner-btn:active {
  transform: scale(0.95);
}

.banner-indicator {
  position: absolute;
  bottom: 30rpx;
  width: 100%;
  display: flex;
  justify-content: center;
  z-index: 99;
}

.indicator-dot {
  width: 24rpx;
  height: 6rpx;
  background-color: rgba(202, 202, 202, 0.5);
  transition: all 0.3s;
}

.indicator-dot.active {
  background-color: #14cc60;
}



.search {
  border-radius: 30px;
  margin: 0 20rpx;
  z-index: 999;
  overflow: hidden;
}

.min-h-100 {
  min-height: 100vh;
}

.centered {
  left: 50%;
  transform: translate(-50%, 0);
  width: auto;
}

/* 内容容器样式 */
.content-container {
  position: relative;
  width: 100%;
  height: auto;
  overflow: hidden;
}

/* 内容项样???*/
.content-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  transition: transform 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.35s ease-out;
  opacity: 0;
  transform: translateX(100%);
  z-index: 1;
  will-change: transform, opacity;
  /* 优化渲染性能 */
}

/* 活动状???- 当前显示的页???*/
.content-item.active {
  opacity: 1;
  transform: translateX(0);
  z-index: 2;
  position: relative;
}

/* 上一个页面状???- 向左移出 */
.content-item.prev {
  transform: translateX(-100%);
  opacity: 0;
}

/* 下一个页面状???- 向右等待 */
.content-item.next {
  transform: translateX(100%);
  opacity: 0;
}

.image-110 {
  width: 110rpx;
  height: 110rpx;
}

.image-130 {
  width: 700rpx;
  height: 260rpx;
}

.image-216 {
  width: 216rpx;
  height: 216rpx;
}

.image-75 {
  width: 75rpx;
  height: 75rpx;
}

.image-100 {
  width: 100rpx;
  height: 100rpx;
}

.image-28 {
  width: 28rpx;
  height: 28rpx;
}

.image-205 {
  width: 205rpx;
  height: 205rpx;
}

.image-280 {
  width: 630rpx;
  height: 280rpx;
}

.image-3125 {
  width: 312.5rpx;
  height: 312.5rpx;
}

.padding-5-15 {
  padding: 5rpx 15rpx;
}

.vague-bgfa-8 {
  background-color: rgba(250, 250, 250, 0.8);
  backdrop-filter: blur(15rpx);
}

.highlighted {
  padding: 4rpx 15rpx;
  background-color: #14cc60;
  color: #fff;
  font-weight: normal;
  border-radius: 10rpx;
  transform: scale(0.8);
  margin-left: 10rpx;
}

.activity-empty-box {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.activity-empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 30rpx;
}

.waterfall-column {
  width: 48%;
}

.top-tab-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.top-tab {
  margin: 0 25rpx;
  position: relative;
}

.active-tab {
  color: #14cc60;
  font-weight: bold;
}

.active-tab::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: -5rpx;
  transform: translateX(-50%);
  width: 30rpx;
  height: 4rpx;
  background-color: #14cc60;
  border-radius: 2rpx;
}

.circle-tab-container {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  width: 100%;
}

.circle-tab {
  display: inline-block;
  padding: 10rpx 20rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.circle-tab-active {
  color: #14cc60;
  font-weight: bold;
}

.circle-tab-active::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: -6rpx;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background-color: #14cc60;
  border-radius: 3rpx;
}



.topic-detail {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.topic-detail:active {
  transform: scale(0.99);
}

.topic-detail-header {
  display: flex;
  align-items: center;
}

.topic-detail-cover {
  width: 150rpx;
  height: 150rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.topic-detail-info {
  flex: 1;
  display: flex;
  height: 150rpx;
  flex-direction: column;
  justify-content: space-between;
}

.topic-detail-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.topic-detail-stats {
  font-size: 24rpx;
  color: #888;
  display: flex;
  align-items: center;
}

.topic-detail-stats text:first-child::after {
  margin: 0 6rpx;
  color: #ccc;
}

.topic-detail-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.topic-badge-icon {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #14cc60;
  margin-right: 10rpx;
}

.topic-tag {
  display: inline-block;
  padding: 6rpx 16rpx;
  background-color: #f0f0f000;
  color: #14cc60;
  font-weight: normal;
  border-radius: 10rpx;
  border: 1rpx solid #14cc60;
  transition: all 0.3s ease;
}

.topic-tag:active {
  background-color: rgba(20, 204, 96, 0.1);
  transform: scale(0.98);
}

/* 内容项样???*/
.content-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  transition: transform 0.35s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.35s ease-out;
  /* 使用缓动函数改进动画 */
  opacity: 0;
  transform: translateX(100%);
  z-index: 1;
  will-change: transform, opacity;
  /* 优化渲染性能 */
}

/* 活动状???- 当前显示的页???*/
.content-item.active {
  opacity: 1;
  transform: translateX(0);
  z-index: 2;
  position: relative;
}

/* 上一个页面状???- 向左移出 */
.content-item.prev {
  transform: translateX(-100%);
  opacity: 0;
}

/* 下一个页面状???- 向右等待 */
.content-item.next {
  transform: translateX(100%);
  opacity: 0;
}

/* 话题内容容器 */
.topic-content {
  animation: fade-in 0.3s ease-out;
}

@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}



/* 圈子项样???*/
.circle-item {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  will-change: transform, box-shadow;
}

.circle-item:active {
  transform: scale(0.98);
}

/* 点赞按钮样式 */
.like-btn {
  padding: 4rpx 12rpx;
  border-radius: 30rpx;
  transition: background-color 0.3s;
}

.like-btn-hover {
  background-color: rgba(0, 0, 0, 0.05);
}

/* 话题标签悬停效果 */
.topic-tag-hover {
  background-color: rgba(20, 204, 96, 0.1);
}



/* 项目标题样式 */
.item-title {
  transition: color 0.3s;
}

.item-title:active {
  color: #14cc60;
}

/* 昵称样式 */
.nickname {
  transition: color 0.3s;
}

.nickname:active {
  color: #14cc60;
}
</style>
